package com.quintal.androidtouchcloud.remote.requests;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public class AnswerServerRequest  extends Thread {
	private static final String MODULE = "AnswerServerRequest";
	private String _result;
	private String _uid;
	private String _question;
	private String _answer;
	private String _date;
	private String _nfc_id;
	private String _report_id;
	private String _extra;
	
	public AnswerServerRequest(String uid, String question, String answer, String report_id,String date, String nfc_id,String extra){
		_uid  = uid;
		_question = question;
		_answer = answer;
		_date = date;
		_nfc_id = nfc_id;
		_report_id = report_id;
		_extra = extra;
	}
	public void run(){
		
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("nfcid",_nfc_id+""));
		params.add(new BasicNameValuePair("uid",""+_uid));
		params.add(new BasicNameValuePair("answer",_answer));
		params.add(new BasicNameValuePair("time",_date));
		params.add(new BasicNameValuePair("question",_question));
		params.add(new BasicNameValuePair("report",_report_id));
		params.add(new BasicNameValuePair("extra",_extra));
		
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost("http://aveiro.m-iti.org/touchcloud/user_report.py");
		try {
			Log.i(MODULE, _nfc_id+" "+_uid+" "+_question+" "+_answer+" "+_report_id+" "+_date);
			httpPost.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			InputStream is = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			String test  = sb.toString();
			test = test.replace("\n","");
			set_result(test);
			Log.i(MODULE, "->"+test);
		}
		catch (IOException e) {
			e.printStackTrace();
			_result = "IOERROR";
		} 
		catch (IllegalStateException e) {
			e.printStackTrace();
		} 
	}
	public String get_result() {
		return _result;
	}
	public void set_result(String result) {
		this._result =  result;
	}
}